package com.ns.school.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 微信获取用户信息工具类
 *
 * @author Spark
 */
public class CommonUtil {

    private static final Logger log = LoggerFactory.getLogger(CommonUtil.class);

    /**
     * 读取请求参数
     *
     * @param request
     * @return String
     * @throws IOException
     * @author Spark
     */
    public static String readRequestBody(HttpServletRequest request) {
        InputStream inputStream = null;
        BufferedInputStream buf = null;
        StringBuilder requestJsonBuffer;
        try {
            inputStream = request.getInputStream();
            buf = new BufferedInputStream(inputStream);

            byte[] buffer = new byte[1024];
            requestJsonBuffer = new StringBuilder();
            int a = 0;
            while ((a = buf.read(buffer)) != -1) {
                requestJsonBuffer.append(new String(buffer, 0, a, StandardCharsets.UTF_8));
            }
            String mRequestBody = requestJsonBuffer.toString();
            if (StrUtil.isEmpty(mRequestBody)) {
                return null;
            } else {
                return URLDecoder.decode(mRequestBody, StandardCharsets.UTF_8);// URL解码
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            if (null != buf) {
                try {
                    buf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 读取请求参数 并解析成Map对象
     *
     * @param request
     * @return String
     * @author Spark
     */
    public static SortedMap<String, String> readRequestBodyToMap(HttpServletRequest request) {
        SortedMap<String, String> params = new TreeMap<>();
        Map<?, ?> requestParams = request.getParameterMap();
        for (Object o : requestParams.keySet()) {
            String name = (String) o;
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 防止请求参数太长
            if (valueStr.length() > 3000) {
                valueStr = valueStr.substring(0, 200);
            }
            params.put(name, valueStr);
        }
        return params;
    }

    /**
     * 将json格式的字符串{"name":"admin","retries":"3fff"} 解析成Map对象
     *
     * @param object
     * @return
     */
    public static Map<String, String> jsonToMap(String object) {
        Map<String, String> data = new HashMap<>();
        JSONObject jsonObject = JSON.parseObject(object);
        Set<String> it = jsonObject.keySet();
        for (String key : it) {
            data.put(key, jsonObject.getString(key));
        }
        return data;
    }

    /**
     * 将json格式的字符串{"name":"admin","retries":"3fff"} 解析成Map对象
     *
     * @param object
     * @return
     */
    public static SortedMap<String, String> jsonToSortedMap(String object) {
        SortedMap<String, String> data = new TreeMap<>();
        JSONObject jsonObject = JSON.parseObject(object);
        Set<String> it = jsonObject.keySet();
        for (String key : it) {
            data.put(key, jsonObject.getString(key));
        }
        return data;
    }

    /**
     * 将json格式的字符串{"name":"admin","retries":"3fff"} 解析成Map对象
     *
     * @param object
     * @return
     */
    public static SortedMap<String, String> jsonToSortedMap(Object object) {
        SortedMap<String, String> data = new TreeMap<>();
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(object));
        Set<String> it = jsonObject.keySet();
        for (String key : it) {
            data.put(key, jsonObject.getString(key));
        }
        return data;
    }

    /**
     * 将对象转成Map
     *
     * @param obj
     * @return
     * @throws Exception
     */
    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }

        Map<String, Object> map = new HashMap<>();

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (key.compareToIgnoreCase("class") == 0) {
                continue;
            }
            Method getter = property.getReadMethod();
            Object value = getter != null ? getter.invoke(obj) : null;
            map.put(key, value);
        }

        return map;
    }

    /**
     * 获取请求者IP地址
     *
     * @param request
     * @return
     */
    public static String getRemoteIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (!StringUtils.hasText(ip)) {
            ip = request.getRemoteAddr();
        } else {
            String[] split = ip.split(",");
            for (String s : split) {
                if (StringUtils.hasText(s.trim()) && !"unknown".equalsIgnoreCase(ip)) {
                    ip = s;
                    break;
                }
            }
        }
        return ip;
    }

    private static final Pattern PATTERN_MONEY = Pattern.compile("^((\\d{1,8})|(\\d{1,8}\\.\\d{1,2}))$");

    /**
     * 判断是否是金额格式
     *
     * @param str
     * @return
     */
    public static boolean isMoneyNumber(String str) {
        if (str == null || "".equals(str)) {
            return false;
        }
        Matcher match = PATTERN_MONEY.matcher(str);
        return match.matches();
    }

    /**
     * 将某个对象转换成json格式并发送到客户端
     *
     * @param response
     * @param obj
     * @throws Exception
     */
    public static void sendJsonMessage(HttpServletResponse response, Object obj) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print(JSONObject.toJSONString(obj, JSONWriter.Feature.WriteMapNullValue));
        writer.close();
        response.flushBuffer();
    }


    public static Map<String, Object> getStringObjectMap(List<?> listAll) {
        PageInfo pageInfo = new PageInfo(listAll);
        Map<String, Object> data = new HashMap<String, Object>();
        // 这是layui要求返回的json数据格式
        data.put("code", 0);
        data.put("msg", "");
        // 将全部数据的条数作为count传给前台（一共多少条）
        data.put("count", pageInfo.getTotal());
        // 将分页后的数据返回（每页要显示的数据）
        data.put("data", pageInfo.getList());
        return data;
    }
}
